<?php


namespace Api\Http\Controllers;


use Api\traits\ApiResponse;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use Illuminate\Http\Request;
use Api\Http\Controllers\Controller;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Redis;
use Modules\Member\Http\Requests\OrderRequest;
use EasyWeChat\MiniApp\Application;
use Modules\Shop\Models\Pivots\UserHasCoupons;
use Modules\Shop\Models\Coupon;


/**
 * @group 用户模块
 *
 * @subgroup 用户管理
 * @subgroupDescription CatchAdmin 后台用户管理
 *
 */
class MembersCouponController extends Controller
{
    use ApiResponse;

    public function __construct(
        protected readonly UserHasCoupons $membersCoupon,
        protected readonly Coupon         $coupon
    )
    {
    }

    /**
     * 用户优惠券列表
     *
     * @queryParam department_id int 部门
     * @queryParam page int 页码
     * @queryParam limit int 每页条数
     * @queryParam Membername string 关键字
     * @queryParam email string 邮箱
     * @queryParam status int 状态
     *
     */
    public function index(Request $request)
    {
        $status = $request->get('status');
        $time = Carbon::now()->timestamp;
        $where = [];
        $where2 = [];
        if ($status == 0) {

            $where[] = ['expired_at', '>', $time];
            $where2[] = ['expired_at', '=', 0];
            $where[] = ['status', '=', 0];

        } elseif ($status == 1) {
            $where[] = ['status','=','1'];
        }else{
            $where[] = ['expired_at', '<=', $time];
        }
        $list = $this->membersCoupon::with('coupon')->where('user_id', $this->getLoginUserId())->where('status',$status)
            ->where(function ($query)use($where,$where2){
            $query->where($where)->orWhere($where2);
        })->orderBy('created_at', 'desc')
            ->simplePaginate($request->get('limit', 10))->toArray();
        $data = [];
        foreach ($list['data'] as $value){
            $status = $value['status'];
            $creatTime = $value['created_at'];
            $expireTime = $value['expired_at'];
            $coupon = current($value['coupon']);
            $coupon['status'] = $status;
            $coupon['created_at'] = $creatTime;
            $coupon['expired_at'] = !empty($value['expired_at']) ? date("Y-m-d H:i:s",$expireTime) : '';
            $data[] = $coupon;
        }
        $list['data'] = $data;
        return $this->success('获取成功',$list);
    }


    /**
     * @return \Illuminate\Http\Response
     * 优惠券福利列表
     */
    public function welfareList()
    {
        $now = now()->format('H');

        $where[] = ['status', '=', '1'];
        $where[] = ['type', '=', '2']; //抢购优惠券
        // 查询开始时间小于等于当前时间并且结束时间大于当前时间的事件
        $list = $this->coupon::with('platform')->where($where)->whereDate('date',date("Y-m-d"))->get()->toArray();
        foreach ($list as $k=>$v){
            if($now < $v['start_at'] || $now > $v['end_at']){
                $list[$k]['is_panic'] = 0;
            }else{
                $list[$k]['is_panic'] = 1;
            }
            $memberCoupon = $this->membersCoupon->where('user_id',$this->getLoginUserId())->where('coupon_id',$v['id'])->first();
            if($memberCoupon){
                $list[$k]['is_receive'] = 1;
            }else{
                $list[$k]['is_receive'] = 0;
            }
        }
        return $this->data($list);
    }

    /**
     * @param $id
     * @return \Illuminate\Http\Response|void
     * 抢单
     */
    public function getCoupon($id)
    {
        $couponInfo = $this->coupon->whereColumn('total_num', '>', 'receive_num')->find($id);
        if (empty($couponInfo)) {
            return $this->fail('优惠券信息有误');
        }
        $hour = Carbon::now()->hour;
        if ($hour < $couponInfo['start_at']) {
            return $this->fail('未到抢购时间无法抢券');
        }
        $record = UserHasCoupons::where('status',0)->where(function ($query){
            return $query->where('expired_at', 0)->orWhere('expired_at' ,'>', time());
        })->where('user_id',$this->getLoginUserId())->first();

        if($record){
            return $this->fail('已有未使用的优惠券无法抢购');
        }
        $this->membersCoupon->user_id = $this->getLoginUserId();
        $this->membersCoupon->coupon_id = $id;
        $now = Carbon::now()->timestamp;
        $expire_time = bcadd((string)$now, ($couponInfo->validaty * 86400), 2);
        $this->membersCoupon->expired_at = $expire_time;

        if ($this->membersCoupon->save() && $couponInfo->increment('receive_num')) {
            return $this->success('抢购成功');
        } else {
            return $this->fail('保存失败');
        }
    }


    /**
     * 新增用户
     *
     * @bodyParam Membername string required 用户名
     * @bodyParam password string required 密码
     * @bodyParam email string 邮箱
     * @bodyParam mobile string 手机号
     * @bodyParam department_id int 部门
     * @bodyParam roles integer[] 角色
     * @bodyParam jobs integer[] 职位
     *
     * @responseField data int 新增ID
     *
     * @return false|mixed
     * @throws InvalidArgumentException
     */
    public function store(Request $request)
    {
        $data = $request->all();
        $couponInfo = Coupon::find($data['id']);
        if ($couponInfo->status != 1) {
            return $this->fail('优惠券不可用,联系管理员');
        }
        $expireDate = $couponInfo->validaty;

        $this->membersCoupon->expired_at = bcadd(Carbon::now(), ($expireDate * 86400));
        if ($this->membersCoupon->create($data)) {
            return $this->success('保存成功');
        } else {
            return $this->fail('保存失败');
        }
    }


}
